package NG::Sys::Cached::DBList;
use strict;
use warnings;
use utf8;

use NG::Sys::Cached::List;
our @ISA = qw(NG::Sys::Cached::List);

sub init {
	my $self = shift;
	$self->SUPER::init;
	unless($self->{table}){
		die "need table\n";
	}
	unless($self->{dbh}){
		die "need dbh\n";
	}
	$self->{sth}{read} = $self->{dbh}->prepare("select * from `".$self->{table}."` where `".$self->{pkey}."`=?");
	$self->{sth}{delete} = $self->{dbh}->prepare("delete from `".$self->{table}."` where `".$self->{ekey}."`=?");
	$self->{sth}{remove} = $self->{dbh}->prepare("delete from `".$self->{table}."` where `".$self->{pkey}."`=?");
	$self->{sth}{insert} = $self->{dbh}->prepare("insert into `".$self->{table}."` (".
					join(", ",map {"`".$_."`" } @{$self->{fields}}).
					") values (".
					join(", ",("?") x  @{$self->{fields}}).
					")");
}
sub _read_source {
	my $self = shift;
	my $id = shift;
	my $sth = $self->{sth}{read};
	$sth->execute($id);
	my $ret = $sth->fetchall_arrayref({});
	#$ret ||= [];
	return $ret;
}
sub _delete_source {
	my $self = shift;
	my $entry = shift;
	$self->{sth}{delete}->execute($entry);
}
sub _delete_source_ary {
	my $self = shift;
	my $entryes = shift;
	my $sth;
	unless($sth = $self->{sth}{delete_ary}[@$entryes]){
		$sth = $self->{sth}{delete_ary}[@$entryes] = $self->{dbh}->prepare(
			"delete from `".$self->{table}."` where `".$self->{ekey}."` in (".join(",", ("?") x @$entryes).")"
			);
	}
	$sth->execute(@$entryes);
}
sub _remove_source {
	my $self = shift;
	my $pid = shift;
	$self->{sth}{remove}->execute($pid);
}
sub _insert_source {
	my $self = shift;
	my $row = shift;
	$self->{sth}{insert}->execute(@{$row}{@{$self->{fields}}});
	my $last_id = $self->{sth}{insert}{mysql_insertid};
	return $last_id;
}
sub _update_source {
	my $self = shift;
	my ($data,$keys) = @_;
	my @keys =  sort @$keys;
	my $key = "update:".join(":",@keys);
	my $sth;
	unless($sth = $self->{sth}{$key}){
		my $sql = "update `".$self->{table}."` set ".
				join(", ",map {"`".$_."`=?"} @keys).
				" where `".$self->{ekey}."`=?";
		$sth = $self->{sth}{$key} = $self->{dbh}->prepare($sql);
		#print "SQL: $sql\n";
		#print join("\n",@{$data}{@keys},$data->{$self->{ekey}},"");
	}
	$sth->execute(@{$data}{@keys},$data->{$self->{ekey}});
}
1;
